package com.heima.comment.config;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Slf4j
public class ApTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        Optional<String> optional = Optional.ofNullable(token);
        if(optional.isPresent()) {
            //2.解析token,获取用户id
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if (claimsBody != null){
                Integer userId = (Integer) claimsBody.get("id");
                //3.存入threadLocal中
                ApUser apUser = new ApUser();
                apUser.setId(userId );
                ApThreadLocalUtil.setUser(apUser);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal...");
        ApThreadLocalUtil.clear();
    }
}
